package main

import (
	"embed"
	"encoding/json"
	"fmt"
	"os"
	"os/exec"
	"slgw_web/application"
	"slgw_web/serial"
	"slgw_web/serial/pac"
	"slgw_web/serial/util"
	"time"

	"net/http"
	_ "net/http/pprof"
	db "slgw_web/application/gormdb"

	"github.com/goburrow/modbus"
	models "openzbox.com/frame/echo/models/sl_gw01"
)

//go:embed web/*
var webroot embed.FS

func main() {
	InitCollectDataList()
	Cmd()
	db := db.GetDB()
	systemInfo := models.SystemInfo{}
	db.First(&systemInfo)
	if systemInfo.ID != 0 {
		if systemInfo.IsWatchdog == 1 {
			go pac.Watchdog()
		}
	}

	router := application.Router()
	router.StaticFS("/", webroot, "web")
	serial.SerialStart()

	// 启动内存分析服务
	go func() {
		http.ListenAndServe(":6060", nil)
	}()
	router.Start(":80")
}

func Cmd() {

	eth := []models.EthSetting{}
	db := db.GetDB()
	db.Find(&eth)
	content := ""
	for _, e := range eth {
		if e.Type != 3 {
			content += "nameserver " + e.DNS + "\n"
			if e.Type == 2 { //静态ip
				// cmd := exec.Command("ifconfig " + e.Name + " hw ether " + e.MAC)
				cmd := exec.Command("sh", "-c", "ifconfig "+e.Name+" hw ether "+e.MAC+" && ifconfig "+e.Name+" "+e.IP+" netmask "+e.NetMask+" && route add default gw "+e.Gateway+" "+e.Name)
				cmd.Stdout = os.Stdout
				cmd.Stderr = os.Stderr
				err := cmd.Run()
				if err != nil {
					fmt.Println(1, "以太网"+e.Name+"配置失败:"+err.Error())
				} else {
					fmt.Println("以太网" + e.Name + "配置成功")
				}
			} else if e.Type == 1 {
				//动态ip
				cmd := exec.Command("sh", "-c", "udhcpc -i "+e.Name)
				cmd.Stdout = os.Stdout
				cmd.Stderr = os.Stderr
				err := cmd.Run()
				if err != nil {
					fmt.Println(1, "以太网"+e.Name+"配置失败:"+err.Error())
				} else {
					fmt.Println("以太网" + e.Name + "配置成功")
				}
			}
			time.Sleep(100 * time.Millisecond)
		}
	}
	if content != "" {
		WriteDNS(content)
	}
}
func WriteDNS(content string) {
	filePath := "/etc/resolv.conf"
	file, err := os.OpenFile(filePath, os.O_WRONLY|os.O_TRUNC, 0644)
	if err != nil {
		fmt.Println("无法打开resolv.conf文件:", err)
		return
	}
	defer file.Close()

	// 清空文件内容
	err = file.Truncate(0)
	if err != nil {
		fmt.Println("清空resolv.conf内容失败:", err)
		return
	}

	// 要写入的内容
	//content := "nameserver 8.8.8.8\nnameserver 8.8.4.4\n"

	// 写入内容到文件
	_, err = file.WriteString(content)
	if err != nil {
		fmt.Println("写入resolv.conf文件失败:", err)
		return
	}

	fmt.Println("已成功写入DNS内容")
}

// 吧数据库采集数据拿到系统缓存
func InitCollectDataList() {
	db := db.GetDB()
	collectDataSession := models.CollectDataSession{}
	db.First(&collectDataSession)
	jsonData := collectDataSession.CollectDataList
	if jsonData != "0" {
		// 创建一个 CollectDataList 切片
		CollectDataList := util.CollectDataList
		// 将 JSON 数据解析到 CollectDataList 中
		err := json.Unmarshal([]byte(jsonData), &CollectDataList)
		if err != nil {
			util.Error("数据缓存错误:", err)
		} else {
			util.CollectDataList = CollectDataList
		}
	}
}

// 测试获取功能码1和2的特殊位数
func test1o2() {
	clients := modbus.NewRTUClientHandler("COM2")
	clients.BaudRate = 9600
	clients.DataBits = 8
	clients.Parity = "N"
	clients.StopBits = 1
	clients.SlaveId = 1
	clients.Timeout = 10 * time.Second
	var clientClients = modbus.NewClient(clients)
	address := uint16(0)   // 寄存器起始地址
	quantity := uint16(16) // 寄存器数量
	results, err := clientClients.ReadDiscreteInputs(address, quantity)
	if err != nil {
		fmt.Println("ReadCoils失败", err)
	} else {
		hexString := pac.Ab2hex(results)
		fmt.Println("results", results)
		fmt.Println("hexString", hexString)
	}
	binaryStr := pac.BytesToBinaryString(results)
	fmt.Println("binaryStr", binaryStr)
	b := pac.GetBinaryString(binaryStr)
	fmt.Println(b)
}

//0101 0010 0100 1100
//0100 1010 0011 0010
